/**
 * Copyright 2012 Brigham Young University
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package edu.byu.nlp.util;

import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;

import com.google.common.collect.Ordering;

/**
 * @author rah67
 *
 */
public class Iterators2 {

	private Iterators2() { }

	public static <E> List<E> topN(Iterator<? extends E> it, int n, Comparator<? super E> c) {
		return Heaps.largestN(it, n, true, c);
	}
	
	public static <E extends Comparable<? super E>> E max(Iterator<? extends E> it) {
		return max(it, Ordering.<E>natural());
	}
	
	public static <E extends Comparable<? super E>> E min(Iterator<? extends E> it) {
		return max(it, Collections.reverseOrder());
	}
	
	public static <E> E max(Iterator<? extends E> it, Comparator<? super E> comparator) {
		if (!it.hasNext()) { 
			return null;
		}
		
		E max = it.next();
		while (it.hasNext()) {
			E next = it.next();
			if (comparator.compare(next, max) > 0) {
				max = next;
			}
		}
		return max;
	}
	
	public static <E> Iterator<Enumeration<E>> enumerate(final Iterator<E> iterator) {
		return new Iterator<Enumeration<E>>() {

			private int i = 0;
			
			@Override
			public boolean hasNext() {
				return iterator.hasNext();
			}

			@Override
			public Enumeration<E> next() {
				return new Enumeration<E>(i++, iterator.next());
			}

			@Override
			public void remove() {
				iterator.remove();
			}
			
		};
	}
}
